package cn.aj.exm.service.impl;

import cn.aj.exm.domain.MovieTicket;
import cn.aj.exm.domain.UserMovie;
import cn.aj.exm.exception.GlobalException;
import cn.aj.exm.mapper.MovieTicketMapper;
import cn.aj.exm.result.JsonResult;
import cn.aj.exm.service.IMovieTicketService;
import cn.aj.exm.service.IUserMovieService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GTR
 * @since 2023-01-02
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private IUserMovieService userMovieService;

    @Override
    public JsonResult buyTicket(Long movieId, Integer count) {
        extracted(movieId, count);
        // 查询中间表
        UserMovie userMovie = new UserMovie();
        EntityWrapper<UserMovie> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", 1L);
        wrapper.eq("movie_ticket_id", movieId);
        UserMovie movie = userMovieService.selectOne(wrapper);
        if(movie == null) {
            userMovie.setUserId(1L);
            userMovie.setMovieTicketId(movieId);
            userMovie.setCount(count);
            userMovieService.insert(userMovie); // 添加中间表的数据
        } else {
            movie.setCount(movie.getCount() + count);
            userMovieService.updateById(movie);
        }

        return JsonResult.success();
    }


    /**
    * @Title: extracted
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2023/01/3 0003 0:23
    * @Parameters: [movieId, count]
    * @Return void
     * 库存
    */
    private void extracted(Long movieId, Integer count) {
        MovieTicket movieTicket = selectById(movieId);
        if(movieTicket == null) {
            throw new GlobalException("改票不存在!");
        }
        movieTicket.setStock(movieTicket.getStock() - count);
        updateById(movieTicket); // 修改票数
    }

    /**
    * @Title: sendMovieTicket
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2023/01/3 0003 0:24
    * @Parameters: [movieId, count, userId]
    * @Return cn.aj.exm.result.JsonResult
     * 随机送票
    */
    @Override
    public JsonResult sendMovieTicket(Long movieId, Integer count, Long userId) {
        extracted(movieId, count);
        UserMovie userMovie = new UserMovie();
        userMovie.setUserId(userId);
        userMovie.setMovieTicketId(movieId);
        userMovie.setCount(count);
        userMovieService.insert(userMovie); // 添加中间表的数据
        return JsonResult.success("送票成功!");
    }
}
